package com.xiaotu.config;

import com.xiaotu.util.PropertiesUtil;
import com.xiaotu.util.SpringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.*;

import javax.annotation.PostConstruct;
import java.util.Properties;

/**
 * 静态资源处理器
 *
 * @author zhangxiao
 * @create 2021-01-13 23:14
 */
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    private static final String PREFIX = "config-";

    private static final String SUFFIX = ".properties";

    private static final String DEV = "dev";

    private static final String PRO = "pro";

    @Autowired
    private SpringUtil springUtil;

    @Autowired
    private PropertiesUtil propertiesUtil;

    /**
     * 文件上传路径
     */
    public static String FILE_UPLOAD_PATH;

    /**
     * 资源映射路径
     */
    public static String MAPPING_URL;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(MAPPING_URL).addResourceLocations(
                "file:" + FILE_UPLOAD_PATH);
    }

    @PostConstruct
    public void getCurrentEnvironment() {
        ApplicationContext context = springUtil.getApplicationContext();
        Environment environment = context.getEnvironment();
        String[] activeProfiles = environment.getActiveProfiles();
        Properties properties = null;
        for (String activeProfile : activeProfiles) {
            if (DEV.equals(activeProfile)) {
                properties = propertiesUtil.getProperties(PREFIX + DEV + SUFFIX);
                break;
            } else if (PRO.equals(activeProfile)) {
                properties = propertiesUtil.getProperties(PREFIX + PRO + SUFFIX);
                break;
            }
        }

        MAPPING_URL = properties.getProperty("file.mapping");
        FILE_UPLOAD_PATH = properties.getProperty("fileupload.path");
    }

}
